package de.lgohlke.compress;

import de.lgohlke.collection.SavedSpace;
import de.lgohlke.serializer.ISerializer;
import de.lgohlke.serializer.MessagePackSerializer;

/**
 * <p>StringArrayCompressor class.</p>
 *
 * @author lars
 * @version $Id: $
 */
public class StringArrayCompressor implements ICompressor<String[]>
{
  private final static ICompressor<byte[]>   compressor = new ByteCompressor();
  private final static ISerializer<String[]> serializer = new MessagePackSerializer<String[]>(new String[] {});

  /*
   * (non-Javadoc)
   * @see de.lgohlke.AST.ICompressor#compress(java.lang.Object)
   */
  /**
   * <p>compress.</p>
   *
   * @param value an array of {@link java.lang.String} objects.
   * @return a {@link de.lgohlke.compress.CompressableValue} object.
   */
  public CompressableValue<String[]> compress(final String[] value)
  {
    CompressableValue<String[]> result = null;
    if ((value != null))
    {
      byte[] serialized = serializer.serialize(value);
      CompressableValue<byte[]> voData = compressor.compress(serialized);

      if (voData.isCompressed())
      {
        result = new CompressableValue<String[]>(null, true, voData.getRaw());
      }
      else
      {
        result = new CompressableValue<String[]>(value, false);
      }
    }
    else
    {
      result = new CompressableValue<String[]>(null, false);
    }
    return result;
  }

  /*
   * (non-Javadoc)
   * @see de.lgohlke.AST.ICompressor#decompress(java.lang.Object)
   */
  /** {@inheritDoc} */
  public String[] decompress(final CompressableValue<String[]> vo)
  {
    String[] result = null;
    if (vo != null)
    {
      if (vo.isCompressed())
      {
        if (vo.getRaw() != null)
        {
          CompressableValue<byte[]> compressedVO = new CompressableValue<byte[]>(null, true, vo.getRaw());
          byte[] serialized = compressor.decompress(compressedVO);
          result = serializer.deserialize(serialized);
        }
      }
      else
      {
        result = vo.getValue();
      }
    }

    return result;
  }

  /*
   * (non-Javadoc)
   * @see de.lgohlke.AST.ICompressor#savedSpace(java.lang.Object)
   */
  /** {@inheritDoc} */
  public SavedSpace savedSpace(final CompressableValue<String[]> vo)
  {
    SavedSpace savedSpace = new SavedSpace();

    if ((vo != null) && vo.isCompressed() && (vo.getRaw() != null))
    {
      int compressed = vo.getRaw().length;
      int raw = 0;

      String[] rawData = decompress(vo);
      for (int i = 0; i < rawData.length; i++)
      {
        raw += rawData[i].length();
      }

      savedSpace.setRawSize(raw);
      savedSpace.setSavedSize(raw - compressed);
    }

    return savedSpace;
  }
}
